package com.smartcruise.util.image;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;

import com.smartcruise.MyApplication;
import com.smartcruise.util.FileUtils;
import com.smartcruise.util.ListUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import id.zelory.compressor.Compressor;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by FengChaoQun
 * on 2018/2/28 0028
 */

public class ImageUtils {

    public static String getCompressImageString(String imagePath) {
        try {
            Bitmap bitmap = new Compressor(MyApplication.getInstance()).setMaxHeight(100).setMaxWidth(100)
                    .compressToBitmap(new File(imagePath));
            return convertIconToString(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 图片转成string
     *
     * @param bitmap
     * @return
     */
    public static String convertIconToString(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
        bitmap.compress(Bitmap.CompressFormat.PNG, 50, baos);
        byte[] appicon = baos.toByteArray();// 转为byte数组
        return Base64.encodeToString(appicon, Base64.DEFAULT);

    }

    /**
     * 获取视频文件截图
     *
     * @param path 视频文件的路径
     * @return Bitmap 返回获取的Bitmap
     */
    public static Bitmap getVideoThumb(String path) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        return media.getFrameAtTime();
    }

    /**
     * 获取视频文件缩略图 API>=8(2.2)
     *
     * @param path 视频文件的路径
     * @param kind 缩略图的分辨率：MINI_KIND、MICRO_KIND、FULL_SCREEN_KIND
     * @return Bitmap 返回获取的Bitmap
     */
    public static Bitmap getVideoThumb2(String path, int kind) {
        return ThumbnailUtils.createVideoThumbnail(path, kind);
    }

    public static Bitmap getVideoThumb2(String path) {
        return getVideoThumb2(path, MediaStore.Video.Thumbnails.MICRO_KIND);
    }

    /**
     * Bitmap保存成File
     *
     * @param bitmap input bitmap
     * @param name   output file's name
     * @return String output file's path
     */
    public static String bitmap2File(Bitmap bitmap, String name) {
        File f = new File(FileUtils.getImageTemplePath(), name);
        if (f.exists()) f.delete();
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            return null;
        }
        Log.d("ImageUtils", "f.length():" + f.length());
        return f.getAbsolutePath();
    }

    public static String getVideoTumbPath(String videoPath) {
        Bitmap bitmap = getVideoThumb2(videoPath);
        if (bitmap != null) {
            return bitmap2File(bitmap, FileUtils.getVideoThumName(videoPath));
        }
        return null;
    }


    /**
     * description:获取图片和视频的缩略图
     */
    public static void getCompressedData(final List<String> images, final List<String> videos, Observer<Map<String, String>> observer) {
        Observable.create(new ObservableOnSubscribe<Map<String, String>>() {
            @Override
            public void subscribe(ObservableEmitter<Map<String, String>> observableEmitter) throws Exception {
                Map<String, String> map = new HashMap<>();

                if (ListUtils.isHaveContent(images)) {
                    for (String image : images) {
                        String thumFileName = FileUtils.getFileThumName(image);
                        if (thumFileName == null) {
                            break;
                        }
                        new Compressor(MyApplication.getInstance()).setMaxHeight(100).setMaxWidth(100)
                                .setDestinationDirectoryPath(FileUtils.getImageThumPath())
                                .compressToFile(new File(image), thumFileName);
                        map.put(thumFileName, new File(FileUtils.getImageThumPath(), thumFileName).getAbsolutePath());
                    }
                }

                if (ListUtils.isHaveContent(videos)) {
                    for (String video : videos) {
                        String videoThumPath = getVideoTumbPath(video);
                        if (videoThumPath == null) {
                            break;
                        }
                        String videoThumName = FileUtils.getFileSimpleName(videoThumPath);
                        new Compressor(MyApplication.getInstance()).setMaxHeight(100).setMaxWidth(100)
                                .setDestinationDirectoryPath(FileUtils.getImageThumPath())
                                .compressToFile(new File(videoThumPath), videoThumName);
                        map.put(videoThumName, new File(FileUtils.getImageThumPath(), videoThumName).getAbsolutePath());
                    }
                }

                observableEmitter.onNext(map);
                observableEmitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    public static Observable<Map<String, String>> getCompressedDataObservable(final List<String> images, final List<String> videos) {
        return Observable.create(new ObservableOnSubscribe<Map<String, String>>() {
            @Override
            public void subscribe(ObservableEmitter<Map<String, String>> observableEmitter) throws Exception {
                Map<String, String> map = new HashMap<>();

                if (images != null && !images.isEmpty()) {
                    for (String image : images) {
                        String thumFileName = FileUtils.getFileThumName(image);
                        if (thumFileName == null) {
                            break;
                        }
                        new Compressor(MyApplication.getInstance()).setMaxHeight(100).setMaxWidth(100)
                                .setDestinationDirectoryPath(FileUtils.getImageThumPath())
                                .compressToFile(new File(image), thumFileName);
                        map.put(thumFileName, new File(FileUtils.getImageThumPath(), thumFileName).getAbsolutePath());
                    }
                }

                if (videos != null && !videos.isEmpty()) {
                    for (String video : videos) {
                        String videoThumPath = getVideoTumbPath(video);
                        if (videoThumPath == null) {
                            break;
                        }
                        new Compressor(MyApplication.getInstance()).setMaxHeight(100).setMaxWidth(100)
                                .setDestinationDirectoryPath(FileUtils.getImageThumPath())
                                .compressToFile(new File(videoThumPath), FileUtils.getFileSimpleName(videoThumPath));
                        map.put(FileUtils.getFileSimpleName(videoThumPath), new File(FileUtils.getImageThumPath(), FileUtils.getFileSimpleName(videoThumPath)).getAbsolutePath());
                    }
                }

                observableEmitter.onNext(map);
                observableEmitter.onComplete();
            }
        });
    }


    public static void saveString(String inputText, String filePath) {
        try {
            FileWriter fw = new FileWriter(filePath);
            fw.flush();
            fw.write(inputText);
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
